package com.xiaoq.users.service;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoq.apis.minipro.IMiniproApi;
import com.xiaoq.apis.minipro.MiniProInfo4Vo;
import com.xiaoq.user.endpoint.MiniUniResponse;
import com.xiaoq.web.DefaultMapper;

@SuppressWarnings("deprecation")
@Service
public class MiniProService {
	
	@Reference(interfaceClass=IMiniproApi.class,check=false,version="1.0.0")
	private IMiniproApi miniProApi;

	private static final Logger LOG = LoggerFactory.getLogger(MiniProService.class);

	public MiniUniResponse getUidByCode(String code,String shopId) {
		
		MiniProInfo4Vo miniProInfo = miniProApi.getMiniProSecretByShopId(shopId);
		if(miniProInfo==null){
			return null;
		}
		String appId = miniProInfo.getAppId();
		String appSecret = miniProInfo.getAppSecret();
		LOG.info("小程序获取UnionId的appid为"+appId+"appSecret:"+appSecret);
		String unionIdUrl =  "https://api.weixin.qq.com/sns/jscode2session";
		String accessToken = unionIdUrl+"?js_code="+code
				+"&appId="+appId
				+"&secret="+appSecret
				+"&grant_type=authorization_code";
		HttpGet request = new HttpGet(accessToken);
		HttpClient httpClient = new DefaultHttpClient();
		MiniUniResponse miniUniResponse = null;
		try {
			HttpResponse response = httpClient.execute(request);
			HttpEntity entity =response.getEntity();
			String body = EntityUtils.toString(entity, "utf-8");
			ObjectMapper objectMapper = new DefaultMapper();
			miniUniResponse = objectMapper.readValue(body, MiniUniResponse.class);
			
		} catch (ClientProtocolException e) {
			LOG.error("客户端协议异常", e);
		} catch (IOException e) {
			LOG.error("IO异常", e);
		}
	
		return miniUniResponse;

	}

}
